package com.sky.service.impl;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ReportService reportService;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额数据统计
     * 1.获取统计日期范围的字符串
     * 2.获取日期对应营业额字符串
     * 3.封装vo,返回
     * @param begin
     * @param end
     * @return
     */
    /**
     * 营业额数据统计
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        // 1. 获取日期字符串 例如：2022-10-01,2022-10-02,2022-10-03
        // 1.1 定义集合，存储每一个日期
        ArrayList<LocalDate> dateList = new ArrayList<>();
        // 1.2 从开始那一天遍历到结束那一天
        while (begin.compareTo(end) <= 0) {
            //1.3 将每一天都存储到集合中
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        // 1.4 将集合中的日期字符串以逗号分隔，转为一个字符串
        String dateListStr = StringUtils.join(dateList,",");

        // 2. 获取营业额字符串 例如：406.0,1520.0,75.0
        // SQL: select * from orders where order_time = #{date} and status=5
        // 2.0 定义集合，存储营业额
        ArrayList<Double> amountList = new ArrayList<>();
        // 2.1 遍历集合，获取每一个日期
        for (LocalDate date : dateList) {
            // 2.2 查询当天的营业额，存储到集合中
            Double amount = ordersMapper.getAmountByDateAndStatus(date, Orders.COMPLETED);
            amountList.add(amount==null?0.0:amount);
        }
        // 2.3 将集合中的营业额以逗号分隔，转为一个字符串
        String amountListStr = StringUtils.join(amountList,",");

        // 3. 将营业额和日期字符串封装为vo，返回
        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        turnoverReportVO.setTurnoverList(amountListStr);
        turnoverReportVO.setDateList(dateListStr);
        return turnoverReportVO;
    }

    /**
     * 用户数据统计
     * @param begin
     * @param end
     * @return
     */

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer> newUserList = new ArrayList<>(); //新增用户数
        List<Integer> totalUserList = new ArrayList<>(); //总用户数

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //新增用户数量 select count(id) from user where create_time > ? and create_time < ?
            Integer newUser = getUserCount(beginTime, endTime);
            //总用户数量 select count(id) from user where  create_time < ?
            Integer totalUser = getUserCount(null, endTime);

            newUserList.add(newUser);
            totalUserList.add(totalUser);
        }

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }

    /**
     * 根据时间区间统计订单数量
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end){
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //每天订单总数集合
        List<Integer> orderCountList = new ArrayList<>();
        //每天有效订单数集合
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //查询每天的总订单数 select count(id) from orders where order_time > ? and order_time < ?
            Integer orderCount = reportService.getOrderCount(beginTime, endTime, null);

            //查询每天的有效订单数 select count(id) from orders where order_time > ? and order_time < ? and status = ?
            Integer validOrderCount = reportService.getOrderCount(beginTime, endTime, Orders.COMPLETED);

            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        }

        //时间区间内的总订单数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //时间区间内的总有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //订单完成率
        Double orderCompletionRate = 0.0;
        if(totalOrderCount != 0){
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();

    }

    /**
     * 根据时间区间统计指定状态的订单数量
     * @param beginTime
     * @param endTime
     * @param status
     * @return
     */
    public Integer getOrderCount(LocalDateTime beginTime, LocalDateTime endTime, Integer status) {
        Map map = new HashMap();
        map.put("status", status);
        map.put("begin",beginTime);
        map.put("end", endTime);
        return ordersMapper.countByMap(map);
    }




    /**
     * 根据时间区间统计用户数量
     * @param beginTime
     * @param endTime
     * @return
     */
    public Integer getUserCount(LocalDateTime beginTime, LocalDateTime endTime) {
        Map map = new HashMap();
        map.put("begin",beginTime);
        map.put("end", endTime);
        return userMapper.countByMap(map);
    }

    /**
     * 销量前十统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        // 1. 查询对应时间范围内每个商品以及对应的销量数据
        List<GoodsSalesDTO> salesDTOList  =  ordersMapper.getSaleTop10(begin, end);

        // 2. 定义集合，将商品名称和对应的销量存储到集合中
        ArrayList<String> nameList = new ArrayList<>();
        ArrayList<Integer> numberList = new ArrayList<>();
        for (GoodsSalesDTO salesDTO : salesDTOList) {
            nameList.add(salesDTO.getName());
            numberList.add(salesDTO.getNumber());
        }

        // 3. 将上述两个集合转为字符串，封装到salesTop10ReportVO中，并返回
        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();
        salesTop10ReportVO.setNumberList(StringUtils.join(numberList,","));
        salesTop10ReportVO.setNameList(StringUtils.join(nameList,","));
        return salesTop10ReportVO;

    }

    /**
     * 导出运营数据
     * @param response
     */
    @Override
    public void export(HttpServletResponse response) {
        // 1. 准备数据
        // 1.1 时间范围：近30天
        LocalDateTime begin = LocalDateTime.now().plusDays(-30);
        LocalDateTime end = LocalDateTime.now().plusDays(-1);
        String str = "时间从:" + begin + "到" + end;
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(begin,end);
        // 2. 使用POI读取模板文件
        InputStream inputStream = ClassLoader.getSystemResourceAsStream("static\\运营数据报表模板.xlsx");
        // 3. 往指定的单元格设置数据
        try {
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            XSSFSheet sheet= workbook.getSheetAt(0);
            XSSFRow row2 = sheet.getRow(1);
            XSSFCell cell2_1 = row2.getCell(1);
            //将时间范围数据放到第二行第一例
            cell2_1.setCellValue(str);
            //给第四行第第三列加设置总营业额
            XSSFRow row4 = sheet.getRow(3);
            XSSFCell cell4_3= row4.getCell(2);
            cell4_3.setCellValue(businessDataVO.getTurnover());
            //给第四行第五列设置订单完成率
            XSSFCell cell4_5 = row4.getCell(4);
            cell4_5.setCellValue(businessDataVO.getOrderCompletionRate());
            //给四行第七列新增用户数
            row4.getCell(6).setCellValue(businessDataVO.getNewUsers());
            //给五行第三列设置有效订单
            XSSFRow row5 = sheet.getRow(4);
            row5.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            //给第五行第五列平均客单数
            row5.getCell(4).setCellValue(businessDataVO.getUnitPrice());
            //概览数据设置完毕 然后再是设置明细数据
            for (int i = 0; i < 30; i++) {
                BusinessDataVO businessData = workspaceService.getBusinessData(begin.with(LocalDate.MIN), end.with(LocalDate.MAX));
                //从第八行开始加i行第二列开始一直到第七列设置数据
                XSSFRow row8_i= sheet.getRow(7 + i);
                //设置明细数据的日期
                row8_i.getCell(1).setCellValue(DateTimeFormatter.ofPattern("yyyy-MM-dd").format(begin));
                //设置营业额
                row8_i.getCell(2).setCellValue(businessData.getTurnover());
                //设置有效订单
                row8_i.getCell(3).setCellValue(businessData.getValidOrderCount());
                //设置订单完成率
                row8_i.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                //设置平均客单价
                row8_i.getCell(5).setCellValue(businessData.getUnitPrice());
                //设置新增用户数
                row8_i.getCell(6).setCellValue(businessData.getNewUsers());
                begin.plusDays(1);
                //根据响应将数据写入
                // 4. 将内存中的数据写回浏览器（文件下载）
                // 一般情况，文件下载设置响应头： response.setHeader("content-disposition=attachment;charset=utf-8");

            }
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}

